package com.haoze.nurse.service.impl;

import com.alibaba.fastjson.JSON;
import com.haoze.nurse.dao.NurseFileMapper;
import com.haoze.nurse.dao.NurseOrdersMapper;
import com.haoze.nurse.dto.Element;
import com.haoze.nurse.enumeration.MedicalTypeEnum;
import com.haoze.nurse.enumeration.StateEnum;
import com.haoze.nurse.model.NurseFileDataDetailEntity;
import com.haoze.nurse.service.NurseFileService;
import com.haoze.nurse.service.NurseOrderService;
import com.haoze.nurse.vo.NurseFileData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

//import com.haoze.emr.model.FileIndexDataEntity;

@Service
public class NurseOrderServiceImpl implements NurseOrderService {

    @Resource
    NurseOrdersMapper nurseOrdersMapper;
    @Resource
    NurseFileMapper nurseFileMapper;
    @Resource
    NurseFileService  nurseFileService;

    @Override
    public List<NurseFileData> getDoctorAdviceNodes(String json) {
        Map<String, Object> map = (Map) JSON.parse(json);

        List fileList = (List) map.get("fileList");
        fileList.add("simpleName");
        fileList.add("orderNo");
        fileList.add("administration");
        fileList.add("orderSubNo");

        String inpatNum = (map.get("inpatNum") == null) ? "" : String.valueOf(map.get("inpatNum"));

        String adviceIds = String.valueOf(map.get("adviceIds"));
        String[] adviceArr = adviceIds.split(",");

        // 获取选中的医嘱列表数据
        List<Map<String, String>> list = nurseOrdersMapper.queryPatientOrdersByIds(adviceArr);


        // 处理选中的医嘱只保留选中的字段
        for (Map<String, String> map1 : list) {
            //选择医嘱的时候获取药品的名称简写
            int index1 =-1;
            int index2 =-1 ;
            int index3 = -1;
            int index4 =-1;
            String conet ="";
            if(map1.get("ordersItem")!=null) {
                index1 = map1.get("ordersItem").toString().indexOf('(');
                index1 = (index1==-1) ?-1: (index1+1);
                index2 = map1.get("ordersItem").toString().indexOf(')');
                index3 = map1.get("ordersItem").toString().indexOf('（');
                index3 = (index3==-1) ?-1: (index3+1);
                index4 = map1.get("ordersItem").toString().indexOf('）');
            }
            if((index1!=-1 && index2!=-1)){ conet = map1.get("ordersItem").toString().substring(index1,index2); }
            if((index3!=-1 && index4!=-1)){ conet = map1.get("ordersItem").toString().substring(index3,index4); }
            if((index1!=-1 && index4!=-1)){ conet = map1.get("ordersItem").toString().substring(index1,index4); }
            if((index3!=-1 && index2!=-1)){ conet = map1.get("ordersItem").toString().substring(index3,index2); }
            if(!conet.equals("")) {
                //获取到drug_name名字，查询到是否有，条件是
                //String drugCode = map1.get("drugCode");
                String simpleName =  nurseOrdersMapper.queryByDrugName(conet);
                if(StringUtils.isNotBlank(simpleName)){
                    map1.put("simpleName", conet);
                }else{
                    map1.put("simpleName", "");
                }
            }

            for (String key : map1.keySet()) {
                boolean change = true;
                for (Object obj : fileList) {
                    String str = (String) obj;
                    // 需要的字段包含
                    if (key.equals(str)) { change = false; }
                }
                if (change == true) { map1.put(key, ""); }
            }
            if (map.get("elementId")!=null) {
                map1.put("elementId", map.get("elementId").toString());
            }
        }


        List<NurseFileData> emrFileDataList = new ArrayList<>();

        if (map.get("varCode").equals(StateEnum.HL_XSERLMC.getValue()) || map.get("varCode").equals(StateEnum.HL_RLZ.getValue()) || map.get("varCode").equals(StateEnum.HL_RLMC.getValue())) {
            // 遍历所有医嘱组装为入量名称和入量值成对的节点
            // 根据varCode获取入量名称和入量值的elementId
            String inElementId = nurseFileMapper.queryVarValueByVarCode(StateEnum.HL_RL.getValue());
            String inNameElementId = nurseFileMapper.queryVarValueByVarCode(StateEnum.HL_RLMC.getValue());
            if (map.get("varCode").equals(StateEnum.HL_XSERLMC.getValue())) {
                inNameElementId = nurseFileMapper.queryVarValueByVarCode(StateEnum.HL_XSERLMC.getValue());
            }
            String inValueElementId = nurseFileMapper.queryVarValueByVarCode(StateEnum.HL_RLZ.getValue());
            String printElementId = nurseFileMapper.queryVarValueByVarCode(StateEnum.HL_RLYC.getValue());

            String inPipeElementId = nurseFileMapper.queryElementIdByElementName("入量导管");
            String inFixWellElementId = nurseFileMapper.queryElementIdByElementName("入量固定良好");
            String inOpenElementId = nurseFileMapper.queryElementIdByElementName("入量通畅");
            String inHideElementId = nurseFileMapper.queryElementIdByElementName("入量隐藏");
            String inUnitElementId = nurseFileMapper.queryElementIdByElementName("护理入量单位");
            String inRLElementId = nurseFileMapper.queryVarValueByVarCode(StateEnum.CK_JLRLBW.getValue());
            String inRLVElementId = nurseFileMapper.queryElementIdByElementName("入量部位");

            // 用于过滤组医嘱多余用法
            Set<String> set = new HashSet<>();

            // 用于只保留组医嘱orderNo和administration
            Map<String, Integer> map1 = new HashMap();

            // 遍历所有医嘱将所有医嘱组装为节点结构
            for (Map<String, String> orderMap : list) {

                String ordersRemark = orderMap.get("ordersRemark") == null ? "" : String.valueOf(orderMap.get("ordersRemark"));
                String ordersItem = orderMap.get("ordersItem") == null ? "" : String.valueOf(orderMap.get("ordersItem"));
                String itemDosage = orderMap.get("itemDosage") == null ? "" : String.valueOf(orderMap.get("itemDosage"));
                String unit = orderMap.get("unit") == null ? "" : String.valueOf(orderMap.get("unit"));
                String simpleName = orderMap.get("simpleName") == null ? "" : String.valueOf(orderMap.get("simpleName"));
                String orderNo = orderMap.get("orderNo") == null ? "" : String.valueOf(orderMap.get("orderNo"));
                String orderSubNo = orderMap.get("orderSubNo") == null ? "" : String.valueOf(orderMap.get("orderSubNo"));
                String administration = orderMap.get("administration") == null ? "" : String.valueOf(orderMap.get("administration"));
                String sum = orderMap.get("sum") == null ? "" : String.valueOf(orderMap.get("sum"));

                // 通过医嘱特殊用法字典替换用法
                String usage = nurseFileMapper.querySpecialUsage(administration);
                if (usage!=null && usage.length()>2) {
                    String[] usageArray = usage.split("、");
                    if (usageArray.length==2) {
                        administration = usageArray[1];
                    }
                }

                // 入量拼装节点
                NurseFileData inEmrFileData = new NurseFileData();
                Element inElement = nurseFileMapper.queryElementById(inElementId);
                NurseFileDataDetailEntity inFileIndexDataEntity = new NurseFileDataDetailEntity();
                inFileIndexDataEntity.setVarCode(inElement.getVarCode());
                inFileIndexDataEntity.setDataValue("入量");
                inFileIndexDataEntity.setDataCode("");
                inFileIndexDataEntity.setElementType(inElement.getType());
                inFileIndexDataEntity.setElementId(inElement.getId());
                inFileIndexDataEntity.setElementProperty(inElement.getElementPropertyFormat());
                inFileIndexDataEntity.setShowIdentification("0");
                inFileIndexDataEntity.setPrintIdentification("0");
                inFileIndexDataEntity.setDeleteIdentification("0");
                inFileIndexDataEntity.setEditIdentification("0");
                List inList = new ArrayList();
                inEmrFileData.setFileIndexDataEntity(inFileIndexDataEntity);
                inEmrFileData.setEmrFileDataList(inList);


                // 入量名称拼装节点
                NurseFileData inNameEmrFileData = new NurseFileData();

                Element inNameElement = nurseFileMapper.queryElementById(inNameElementId);
                inNameEmrFileData.setElement(inNameElement);
                NurseFileDataDetailEntity inNameFileIndexDataEntity = new NurseFileDataDetailEntity();

                if (set.contains(orderNo)) {
                    Integer total = map1.get(orderNo);
                    total++;
                    map1.put(orderNo, total);
                } else {
                    map1.put(orderNo, 1);
                    set.add(orderNo);
                }

                // TODO: 暂时写成默认值
                inNameFileIndexDataEntity.setDataValue(simpleName.equals("") ? ordersItem : simpleName);
                inNameFileIndexDataEntity.setDataCode("");
                inNameFileIndexDataEntity.setVarCode(inNameElement.getVarCode());
                inNameFileIndexDataEntity.setElementId(inNameElement.getId());
                inNameFileIndexDataEntity.setElementProperty(inNameElement.getElementPropertyFormat());
                inNameFileIndexDataEntity.setElementType(inNameElement.getType());
                inNameFileIndexDataEntity.setShowIdentification("0");
                inNameFileIndexDataEntity.setPrintIdentification("0");
                inNameFileIndexDataEntity.setDeleteIdentification("0");
                inNameFileIndexDataEntity.setEditIdentification("0");

                Map<String, String> expandMap = new HashMap<>();
                expandMap.put("orderNo", orderNo);
                expandMap.put("orderSubNo", orderSubNo);
                expandMap.put("administration", administration);
                expandMap.put("ordersRemark", ordersRemark);
                expandMap.put("fullName", ordersItem);

                inNameFileIndexDataEntity.setExpandFieldsMap(expandMap);
                inNameEmrFileData.setFileIndexDataEntity(inNameFileIndexDataEntity);
                inNameEmrFileData.setEmrFileDataList(new ArrayList<>());
//                fileIndexDataEntity.setDataStatus(sum);
                inList.add(inNameEmrFileData);

                // 入量固定良好拼装================================================
                NurseFileData inFixEmrFileData = new NurseFileData();

                Element inFixElement = nurseFileMapper.queryElementById(inFixWellElementId);

                inFixEmrFileData.setElement(inFixElement);
                NurseFileDataDetailEntity inFixFileIndexDataEntity = new NurseFileDataDetailEntity();
                inFixFileIndexDataEntity.setDataValue("");
                inFixFileIndexDataEntity.setDataCode("");
                inFixFileIndexDataEntity.setVarCode(inFixElement.getVarCode());
                inFixFileIndexDataEntity.setElementType(inFixElement.getType());
                inFixFileIndexDataEntity.setElementId(inFixElement.getId());
                inFixFileIndexDataEntity.setElementProperty(inFixElement.getElementPropertyFormat());
                inFixFileIndexDataEntity.setShowIdentification("0");
                inFixFileIndexDataEntity.setPrintIdentification("0");
                inFixFileIndexDataEntity.setDeleteIdentification("0");
                inFixFileIndexDataEntity.setEditIdentification("0");

                inFixEmrFileData.setFileIndexDataEntity(inFixFileIndexDataEntity);
                inFixEmrFileData.setEmrFileDataList(new ArrayList<>());
                inList.add(inFixEmrFileData);

                // 入量通畅拼装
                NurseFileData inOpenEmrFileData = new NurseFileData();

                Element inOpenElement = nurseFileMapper.queryElementById(inOpenElementId);

                inOpenEmrFileData.setElement(inOpenElement);
                NurseFileDataDetailEntity inOpenFileIndexDataEntity = new NurseFileDataDetailEntity();
                inOpenFileIndexDataEntity.setDataValue("");
                inOpenFileIndexDataEntity.setDataCode("");
                inOpenFileIndexDataEntity.setVarCode(inOpenElement.getVarCode());
                inOpenFileIndexDataEntity.setElementId(inOpenElement.getId());
                inOpenFileIndexDataEntity.setElementType(inOpenElement.getType());
                inOpenFileIndexDataEntity.setElementProperty(inOpenElement.getElementPropertyFormat());
//                inOpenFileIndexDataEntity.setOrderNo(orderNo);
                inOpenFileIndexDataEntity.setShowIdentification("0");
                inOpenFileIndexDataEntity.setPrintIdentification("0");
                inOpenFileIndexDataEntity.setDeleteIdentification("0");
                inOpenFileIndexDataEntity.setEditIdentification("0");
                inOpenEmrFileData.setFileIndexDataEntity(inOpenFileIndexDataEntity);

                inOpenEmrFileData.setEmrFileDataList(new ArrayList<>());
                inList.add(inOpenEmrFileData);


                // 入量值拼装节点
                NurseFileData inValueEmrFileData = new NurseFileData();

                Element inValueElement = nurseFileMapper.queryElementById(inValueElementId);

                inValueEmrFileData.setElement(inValueElement);
                NurseFileDataDetailEntity inValueFileIndexDataEntity = new NurseFileDataDetailEntity();
                inValueFileIndexDataEntity.setDataValue(itemDosage);
                inValueFileIndexDataEntity.setDataCode("");
                inValueFileIndexDataEntity.setUnit(unit);
                inValueFileIndexDataEntity.setVarCode(inValueElement.getVarCode());
                inValueFileIndexDataEntity.setElementId(inValueElement.getId());
                inValueFileIndexDataEntity.setElementType(inValueElement.getType());
                inValueFileIndexDataEntity.setElementProperty(inValueElement.getElementPropertyFormat());
//                inOpenFileIndexDataEntity.setOrderNo(orderNo);
                inValueFileIndexDataEntity.setShowIdentification("0");
                inValueFileIndexDataEntity.setPrintIdentification("0");
                inValueFileIndexDataEntity.setDeleteIdentification("0");
                inValueFileIndexDataEntity.setEditIdentification("0");
                inValueEmrFileData.setFileIndexDataEntity(inValueFileIndexDataEntity);

                inValueEmrFileData.setEmrFileDataList(new ArrayList<>());
                inList.add(inValueEmrFileData);

                // 入量单位拼装节点
                NurseFileData inUnitEmrFileData = new NurseFileData();

                Element inUnitElement = nurseFileMapper.queryElementById(inUnitElementId);

                inUnitEmrFileData.setElement(inUnitElement);
                NurseFileDataDetailEntity inUnitFileIndexDataEntity = new NurseFileDataDetailEntity();
                inUnitFileIndexDataEntity.setDataValue(unit);
                inUnitFileIndexDataEntity.setDataCode("");
                inUnitFileIndexDataEntity.setUnit(unit);
                inUnitFileIndexDataEntity.setVarCode(inUnitElement.getVarCode());
                inUnitFileIndexDataEntity.setElementId(inUnitElement.getId());
                inUnitFileIndexDataEntity.setElementType(inUnitElement.getType());
                inUnitFileIndexDataEntity.setElementProperty(inUnitElement.getElementPropertyFormat());
//                inUnitFileIndexDataEntity.setOrderNo(orderNo);
                inUnitFileIndexDataEntity.setShowIdentification("0");
                inUnitFileIndexDataEntity.setPrintIdentification("0");
                inUnitFileIndexDataEntity.setDeleteIdentification("0");
                inUnitFileIndexDataEntity.setEditIdentification("0");
                inUnitEmrFileData.setFileIndexDataEntity(inUnitFileIndexDataEntity);

                inUnitEmrFileData.setEmrFileDataList(new ArrayList<>());
                inList.add(inUnitEmrFileData);

                // 入量隐藏拼装节点
                NurseFileData inHideEmrFileData = new NurseFileData();

                Element inHideElement = nurseFileMapper.queryElementById(inHideElementId);

                inHideEmrFileData.setElement(inHideElement);
                NurseFileDataDetailEntity inHideFileIndexDataEntity = new NurseFileDataDetailEntity();
                inHideFileIndexDataEntity.setDataValue("");
                inHideFileIndexDataEntity.setDataCode("");
                inHideFileIndexDataEntity.setVarCode(inUnitElement.getVarCode());
                inHideFileIndexDataEntity.setElementId(inUnitElement.getId());
                inHideFileIndexDataEntity.setElementType(inUnitElement.getType());
                inHideFileIndexDataEntity.setElementProperty(inUnitElement.getElementPropertyFormat());
//                inUnitFileIndexDataEntity.setOrderNo(orderNo);
                inHideFileIndexDataEntity.setShowIdentification("0");
                inHideFileIndexDataEntity.setPrintIdentification("0");
                inHideFileIndexDataEntity.setDeleteIdentification("0");
                inHideFileIndexDataEntity.setEditIdentification("0");
                inHideEmrFileData.setFileIndexDataEntity(inHideFileIndexDataEntity);

                inHideEmrFileData.setEmrFileDataList(new ArrayList<>());
                inList.add(inHideEmrFileData);

/////////////加入导管部位封装节点   /////////////////////////////////////////////////////////////////////////////////
                // 入量部位拼装节点
                NurseFileData inRLEmrFileData = new NurseFileData();
                Element inRlbwElement = nurseFileMapper.queryElementById(inRLElementId);
                inRLEmrFileData.setElement(inRlbwElement);

                NurseFileDataDetailEntity inRlFileIndexDataEntity = new NurseFileDataDetailEntity();
                inRlFileIndexDataEntity.setDataValue("");
                inRlFileIndexDataEntity.setDataCode("");
                inRlFileIndexDataEntity.setVarCode(inUnitElement.getVarCode());
                inRlFileIndexDataEntity.setElementId(inUnitElement.getId());
                inRlFileIndexDataEntity.setElementType(inUnitElement.getType());
                inRlFileIndexDataEntity.setElementProperty(inUnitElement.getElementPropertyFormat());
                inRlFileIndexDataEntity.setShowIdentification("0");
                inRlFileIndexDataEntity.setPrintIdentification("0");
                inRlFileIndexDataEntity.setDeleteIdentification("0");
                inRlFileIndexDataEntity.setEditIdentification("0");
                inRLEmrFileData.setFileIndexDataEntity(inHideFileIndexDataEntity);
                inRLEmrFileData.setEmrFileDataList(new ArrayList<>());

                inList.add(inRLEmrFileData);
                emrFileDataList.add(inEmrFileData);

            }

            // 清除非组医嘱的orderNo和administration
            for (NurseFileData nurseFileData:emrFileDataList) {
                NurseFileData inNameNurseFileData = nurseFileData.getEmrFileDataList().get(0);
                Map<String, String> expandFields = inNameNurseFileData.getFileIndexDataEntity().getExpandFieldsMap();
                if (expandFields!=null) {
                    String orderNo = expandFields.get("orderNo");
                    if (orderNo!=null && orderNo.length() > 0) {
                        expandFields.put("orderSum", String.valueOf(map1.get(orderNo)));
                        if (map1.get(orderNo)==1) {
                            expandFields.put("orderSubNo", "");
                        }
                    }
                }
            }

            return emrFileDataList;

        } else if (map.get("varCode").equals(StateEnum.HL_BQJHL.getValue()) || map.get("varCode").equals(StateEnum.HL_BQJHLJD.getValue())) {
            // 护理病情及护理

            // 用于过滤组医嘱多余用法
            Set<String> set = new HashSet<>();
            // 用于只保留组医嘱orderNo和administration
            Map<String, String> map1 = new HashMap();
            map1.put("begin", "");
            map1.put("middle", "");
            map1.put("end", "");

            Map<String, NurseFileDataDetailEntity> entityMap = new HashMap<>();

            // 遍历所有医嘱将所有医嘱组装为节点结构
            for (Map<String, String> orderMap : list) {

                String orderNo = orderMap.get("orderNo") == null ? "" : String.valueOf(orderMap.get("orderNo"));
//                String orderSubNo = orderMap.get("orderSubNo") == null ? "" : String.valueOf(orderMap.get("orderSubNo"));
                String ordersItem = orderMap.get("ordersItem") == null ? "" : String.valueOf(orderMap.get("ordersItem"));
                String simpleName = orderMap.get("simpleName") == null ? "" : String.valueOf(orderMap.get("simpleName"));

                NurseFileData emrFileData = new NurseFileData();

                Element element = new Element();
                String elementId = nurseFileMapper.querySysElementId(com.haoze.nurse.enumeration.StateEnum.MB_WB.getValue());
                element.setId(elementId);
                element.setName("文本数据元");
                element.setDataCode("");
                element.setDataValue("");
                element.setVarCode(StateEnum.MB_WB.getValue());
                element.setType("1");
                emrFileData.setElement(element);

                if (set.contains(orderNo)) {
                    String srcMiddle = map1.get("middle");

                    String middle = (simpleName.equals("") ? ordersItem : simpleName + " ") +
                            (orderMap.get("itemDosage") == null ? "" : String.valueOf(orderMap.get("itemDosage")) + " ") +
                            (orderMap.get("unit") == null ? "" : String.valueOf(orderMap.get("unit")) + " ");
                    map1.put("middle", srcMiddle + " 加 " + middle);
                    String dataValue = map1.get("begin") + map1.get("middle") + map1.get("end");
                    NurseFileDataDetailEntity tempFileIndexDataEntity = entityMap.get(orderNo);
                    tempFileIndexDataEntity.setDataValue(dataValue);
                } else {
                    // 拼装dataValue
                    String begin = (orderMap.get("ordersClass") == null ? "" : String.valueOf(orderMap.get("ordersClass")) + " ") +
                            (orderMap.get("planBeginDatetime") == null ? "" : String.valueOf(orderMap.get("planBeginDatetime")) + " ");
                    map1.put("begin", begin);

                    String middle = (simpleName.equals("") ? ordersItem : simpleName + " ") +
                            (orderMap.get("itemDosage") == null ? "" : String.valueOf(orderMap.get("itemDosage")) + " ") +
                            (orderMap.get("unit") == null ? "" : String.valueOf(orderMap.get("unit")) + " ");
                    map1.put("middle", middle);

                    String administration = orderMap.get("administration") == null ? "" : String.valueOf(orderMap.get("administration"));
                    // 通过医嘱特殊用法字典替换用法
                    String usage = nurseFileMapper.querySpecialUsage(administration);
                    if (usage!=null && usage.length()>2) {
                        String[] usageArray = usage.split("、");
                        if (usageArray.length == 2) {
                            administration = usageArray[1];
                        }
                    }

                    String end = (administration + " ") +
                            (orderMap.get("ordersRemark") == null ? "" : String.valueOf(orderMap.get("ordersRemark")) + " ") +
                            (orderMap.get("freq") == null ? "" : String.valueOf(orderMap.get("freq")) + " ") +
                            (orderMap.get("planEndDatetime") == null ? "" : String.valueOf(orderMap.get("planEndDatetime")) + " ") +
                            (orderMap.get("userName") == null ? "" : String.valueOf(orderMap.get("userName")) + " ") +
                            (orderMap.get("createDatetime") == null ? "" : String.valueOf(orderMap.get("createDatetime")) + " ") +
                            (orderMap.get("execDatetime") == null ? "" : String.valueOf(orderMap.get("execDatetime")) + " ") +
                            (orderMap.get("execUserName") == null ? "" : String.valueOf(orderMap.get("execUserName")) + " ");
                    map1.put("end", end);

                    set.add(orderNo);

                    // 拼装dataValue
                    String dataValue = map1.get("begin") + map1.get("middle") + map1.get("end");

                    NurseFileDataDetailEntity fileIndexDataEntity = new NurseFileDataDetailEntity();
                    fileIndexDataEntity.setDataValue(dataValue);
                    fileIndexDataEntity.setElementId(map.get("elementId")!=null ? map.get("elementId").toString() : "");
                    fileIndexDataEntity.setShowIdentification("0");
                    fileIndexDataEntity.setPrintIdentification("0");
                    fileIndexDataEntity.setDeleteIdentification("0");
                    fileIndexDataEntity.setEditIdentification("1");
                    fileIndexDataEntity.setElementId(elementId);
//                    fileIndexDataEntity.setVarCode(StateEnum.MB_WB.getValue());
                    emrFileData.setFileIndexDataEntity(fileIndexDataEntity);
                    emrFileData.setEmrFileDataList(new ArrayList<>());
                    emrFileDataList.add(emrFileData);

                    entityMap.put(orderNo, fileIndexDataEntity);
                }
            }
        }

        return emrFileDataList;
    }

}
